//
//  WLANView.m
//  upnpxdemo
//
//  Created by a  on 13-8-26.
//  Copyright (c) 2013年 wiimu.inc. All rights reserved.
//

#import "WLANView.h"
#import <QuartzCore/QuartzCore.h>
#import "JSONKit.h"

#define BACKALPHA 0.7

@interface WLANView()
{
    NSArray * wlanArr;
    int currentSelectedDevice;
    BOOL isSkip;
    
    NSTimer * connectStatusTimer;
//    int connectTimeCount;//用于在硬件发生错误时处理；20s超时，报错，不再连接。
    
    NSString * currentConnectedDevice;
}
@property (retain) NSArray * wlanArr;
@property (retain) NSString * currentConnectedDevice;

@end

@implementation WLANView
@synthesize wlanArr;
@synthesize currentConnectedDevice;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)awakeFromNib
{
    isSkip = NO;
//    connectTimeCount = 0;
    
    [self prepareUI];
    [self appearAnimation];
}

-(IBAction)skipButtonPressed:(id)sender
{
    if(connectStatusTimer != nil && [connectStatusTimer isValid])
    {
        [connectStatusTimer invalidate];
        connectStatusTimer = nil;
    }
    
    isSkip = YES;
    [self disappearAnimation];
}

#pragma mark - private methods
-(void)appearAnimation
{
    CABasicAnimation *forwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    forwardAnimation.duration = 0.2f;
    forwardAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.5f :1.7f :0.6f :0.85f];
    forwardAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    forwardAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    [_insideView.layer addAnimation:forwardAnimation forKey:@"popin"];
    
    CABasicAnimation *fadein = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadein.toValue = [NSNumber numberWithFloat:BACKALPHA];
    fadein.duration = 0.2;
    fadein.fillMode = kCAFillModeForwards;
    fadein.removedOnCompletion = NO;
    fadein.delegate = self;
    [_backView.layer addAnimation:fadein forKey:@"fadein"];
}

-(void)disappearAnimation
{
    self.skipButton.hidden = YES;
    
    if(connectStatusTimer != nil && [connectStatusTimer isValid])
    {
        [connectStatusTimer invalidate];
        connectStatusTimer = nil;
    }
    
    CABasicAnimation *fadeout = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeout.toValue = [NSNumber numberWithFloat:0];
    fadeout.duration = 0.2f;
    fadeout.fillMode = kCAFillModeForwards;
    fadeout.removedOnCompletion = NO;
    fadeout.delegate = self;
    [_backView.layer addAnimation:fadeout forKey:@"fadeout"];
    
    CABasicAnimation *reverseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    reverseAnimation.duration = 0.2f;
    reverseAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.4f :0.15f :0.5f :-0.7f];
    reverseAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    reverseAnimation.toValue = [NSNumber numberWithFloat:0.0f];
    reverseAnimation.delegate = self;
    reverseAnimation.removedOnCompletion = NO;
    reverseAnimation.fillMode = kCAFillModeForwards;
    [_insideView.layer addAnimation:reverseAnimation forKey:@"kLPAnimationKeyPopup"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if(flag)
    {
        if(anim == [_backView.layer animationForKey:@"fadein"])
        {
            self.backView.alpha = BACKALPHA;
            self.skipButton.hidden = NO;
        }
        else if(anim == [_backView.layer animationForKey:@"fadeout"])
        {
            [self removeFromSuperview];
            
            if(isSkip == YES && self.completionBlock)
            {
                self.completionBlock();
            }
        }
        else if(anim == [_passwordView.layer animationForKey:@"pvFadein"])
        {
            _passwordView.alpha = 1;
        }
        else if(anim == [_passwordView.layer animationForKey:@"pvFadeout"])
        {
            _passwordView.alpha = 0;
        }
    }
}

-(void)prepareUI
{
    _titleLabel.text = NSLocalizedString(@"WLANVIEW_TITLE",@"");
    [_skipButton setTitle:NSLocalizedString(@"WLANVIEW_SKIPBUTTON",@"") forState:UIControlStateNormal];
    [_confirmButton setTitle:NSLocalizedString(@"CONFIRM",@"") forState:UIControlStateNormal];
    [_cancelButton setTitle:NSLocalizedString(@"CANCEL",@"") forState:UIControlStateNormal];
    _passwordTitleLabel.text = NSLocalizedString(@"INPUTWLANPASSWORD",@"");
    
    if([[UIDevice currentDevice].systemVersion intValue] < 6)
    {
        _skipButton.frame = CGRectMake(_skipButton.frame.origin.x, _skipButton.frame.origin.y-20, _skipButton.frame.size.width, _skipButton.frame.size.height);
    }
    
    if([GlobalInfo sharedInstance].deviceType == IPHONE4_TYPE)
    {
        _backView.frame = CGRectMake(0, 0, 320, 568);
        _insideView.frame = CGRectMake(_insideView.frame.origin.x, _insideView.frame.origin.y+88, _insideView.frame.size.width, _insideView.frame.size.height);
        _flowerView.frame = _insideView.frame;
        _skipButton.frame = CGRectMake(_skipButton.frame.origin.x, _skipButton.frame.origin.y+88, _skipButton.frame.size.width, _skipButton.frame.size.height);
        _passwordView.frame = CGRectMake(_passwordView.frame.origin.x, _passwordView.frame.origin.y+88, _passwordView.frame.size.width, _passwordView.frame.size.height);
    }
}

-(void)getDeviceInformations
{
    [self getApList];
    [self getCurrentConnectedDevice];
}

-(void)getApList
{ 
    [[GlobalService sharedInstance] getWifiList:self];
}

-(void)getCurrentConnectedDevice
{
    [[GlobalService sharedInstance] getCurrentConnectedDevice:self];
}

-(void)connectTo:(NSString *)ssid andAuth:(NSString *)auth andPass:(NSString *)password andChannel:(NSString *)channel andEncrypt:(NSString *)encrypt
{
    [_skipButton setTitle:NSLocalizedString(@"WLANVIEW_SKIPBUTTON",@"") forState:UIControlStateNormal];
    
//    connectTimeCount = 0;

    [self.insideView makeToast:NSLocalizedString(@"CONNECTTOWIFIANDWAIT",@"")
           duration:3.0
           position:@"bottom"
              title:NSLocalizedString(@"ALERT_TITLE",@"")];
    
    _flowerView.hidden = NO;
    
    [[GlobalService sharedInstance] connectToWifi:self withSsid:ssid andAuth:auth andPass:password andChannel:channel andEncrypt:encrypt];
}

-(NSString *)str2HexStr:(char*)str
{
    char chars[] = "0123456789ABCDEF";
    NSMutableString * sb = [NSMutableString string];
    int bit;
    for (int i = 0; i < strlen(str); i++)
    {
        bit = (str[i] & 0x0f0) >> 4;
        [sb appendFormat:@"%c",chars[bit]];
        bit = str[i] & 0x0f;
        [sb appendFormat:@"%c",chars[bit]];
    }
    return sb;
}

-(void)getConnectStatusTimerMethod
{
//    connectTimeCount++;
    
    [[GlobalService sharedInstance] getWifiConnectStatus:self];
}

#pragma mark -
#pragma mark passwordview methods
-(void)pushInPasswordView
{
    CABasicAnimation *forwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    forwardAnimation.duration = 0.4f;
    forwardAnimation.fromValue = [NSNumber numberWithFloat:self.frame.size.width];
    forwardAnimation.toValue = [NSNumber numberWithFloat:0];
    [_passwordView.layer addAnimation:forwardAnimation forKey:@"pvIn"];
    
    CABasicAnimation *fadein = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadein.fromValue = [NSNumber numberWithFloat:0];
    fadein.toValue = [NSNumber numberWithFloat:1];
    fadein.duration = 0.4;
    fadein.fillMode = kCAFillModeForwards;
    fadein.delegate = self;
    fadein.removedOnCompletion = NO;
    [_passwordView.layer addAnimation:fadein forKey:@"pvFadein"];
}

-(void)pushOutPasswordView
{
    CABasicAnimation *forwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    forwardAnimation.duration = 0.4f;
    forwardAnimation.fromValue = [NSNumber numberWithFloat:0];
    forwardAnimation.toValue = [NSNumber numberWithFloat:self.frame.size.width];
    [_passwordView.layer addAnimation:forwardAnimation forKey:@"pvOut"];
    
    CABasicAnimation *fadein = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadein.fromValue = [NSNumber numberWithFloat:1];
    fadein.toValue = [NSNumber numberWithFloat:0];
    fadein.duration = 0.4;
    fadein.fillMode = kCAFillModeForwards;
    fadein.delegate = self;
    fadein.removedOnCompletion = NO;
    [_passwordView.layer addAnimation:fadein forKey:@"pvFadeout"];
}

-(IBAction)touchDownOnBack:(id)sender
{
    [_passwordField resignFirstResponder];
}

-(IBAction)confirmButtonPressed:(id)sender
{
    [_passwordField resignFirstResponder];
    NSDictionary * dic = [wlanArr objectAtIndex:currentSelectedDevice];
    NSString * password = _passwordField.text;

    //保存密码
    [[GlobalInfo sharedInstance] addWifiInfo:[dic objectForKey:@"ssid"] password:password];
    
//    char * bytes = (char *)[password UTF8String];
//    password = [self str2HexStr:bytes];
    
    [self connectTo:[dic objectForKey:@"ssid"] andAuth:[dic objectForKey:@"auth"] andPass:password andChannel:[dic objectForKey:@"channel"] andEncrypt:[dic objectForKey:@"encry"]];
    [self pushOutPasswordView];
}

-(IBAction)cancelButtonPressed:(id)sender
{
    [_passwordField resignFirstResponder];
    [self pushOutPasswordView];
}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [wlanArr count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    else
    {
        for(UIView * subview in [cell.contentView subviews])
        {
            [subview removeFromSuperview];
        }
    }

    // Configure the cell.
    
    NSDictionary * dic = [wlanArr objectAtIndex:indexPath.row];
    NSString * authStr = [dic objectForKey:@"auth"];
    int dbm = [[dic objectForKey:@"rssi"] intValue];
    
    if(dbm >= 0 && dbm <= 20)
    {
        dbm = 0;
    }
    else if(dbm >= 21 && dbm <= 40)
    {
        dbm = 1;
    }
    else if(dbm >= 41 && dbm <= 60)
    {
        dbm = 2;
    }
    else if(dbm >= 61 && dbm <= 80)
    {
        dbm = 3;
    }
    else if(dbm >= 81 && dbm <= 100)
    {
        dbm = 4;
    }
    
    UIImage * image = nil;
    NSString * imageName = nil;
    if([authStr isEqualToString:@"OPEN"])
    {
        imageName = [NSString stringWithFormat:@"wifi_nlock%d.png",dbm];
    }
    else
    {
        imageName = [NSString stringWithFormat:@"wifi_lock%d.png",dbm];
    }
    
    image = [UIImage imageNamed:imageName];
    
    UIImageView * imageview = [[UIImageView alloc] initWithImage:image];
    [cell.contentView addSubview:imageview];
    [imageview setFrame:CGRectMake(10, 7, 30, 30)];

    UILabel * label = [[UILabel alloc] init];
    label.frame = CGRectMake(50, 4, 150, 40);
    [cell.contentView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:14];
    label.text = [dic objectForKey:@"ssid"];
  
    UIImageView * rightImage = nil;
    if([currentConnectedDevice isEqualToString:[dic objectForKey:@"ssid"]])
    {
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chosen.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-45, 10, 20, 20);
    }
    else
    {
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rightarrow1.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-40, 15, 10, 15);
    }
    
    [cell.contentView addSubview:rightImage];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    NSDictionary * dic = [wlanArr objectAtIndex:indexPath.row];
    NSString * authStr = [dic objectForKey:@"auth"];
    currentSelectedDevice = indexPath.row;
    
    if([authStr isEqualToString:@"OPEN"])
    {
        [self connectTo:[GlobalInfo sharedInstance].currentBaseURL andAuth:[dic objectForKey:@"auth"] andPass:@":NONE" andChannel:[dic objectForKey:@"channel"] andEncrypt:[dic objectForKey:@"encry"]];
    }
    else//输入密码
    {
        _passwordField.text = [[GlobalInfo sharedInstance] getWifiPassword:[dic objectForKey:@"ssid"]];
        
        [self pushInPasswordView];
    }
}

#pragma mark -
#pragma mark servicecallbacks
-(void)serviceGetWifiListCallBack:(NSDictionary*)dicCallBack
{
    _flowerView.hidden = YES;
    
    NSDictionary * tempDic = dicCallBack;
    
    if(tempDic == nil || [[tempDic objectForKey:@"responsestatus"] intValue] != [SERVICE_SUCCESS intValue])
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_CONNECTTODEVICEFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }
    if(tempDic == nil)
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_GETWIFILISTFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }

    NSMutableArray * arr = [NSMutableArray array];
    
    for(NSDictionary * dic in [tempDic objectForKey:@"aplist"])
    {
        NSString * ssidStr = [dic objectForKey:@"ssid"];
        NSString * bssidStr = [dic objectForKey:@"bssid"];
        
        if(ssidStr != nil && [ssidStr length] != 0 && (![ssidStr hasPrefix:@"LinkPlay_"] && ![ssidStr hasPrefix:@"AllCast_"] && ![ssidStr hasPrefix:@"WIFIAudio_"] && ![ssidStr hasPrefix:@"WiFiAudio_"] && ![ssidStr hasPrefix:@"WifiAudio_"] && ![bssidStr hasPrefix:@"00226C"]))
        {
            [arr addObject:dic];
        }
    }
    
    self.wlanArr = arr;
    
    [_wlanTable reloadData];
}

-(void)serviceGetCurrentConnectedDeviceCallBack:(NSDictionary*)dicCallBack
{
    NSString * retstr = [dicCallBack objectForKey:@"responseString"];
    
    if(retstr == nil)
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_GETCONNECTEDDEVICEFAILED",@"")
               duration:3.0
               position:@"bottom"
                  title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }
    
    NSArray * array = [retstr componentsSeparatedByString:@":"];
    if([array count] == 2)//NULL
    {
        self.infoLabel.text = NSLocalizedString(@"UNCONNECTED",@"");
    }
    else if([array count] == 3)
    {
        if([[array objectAtIndex:2] intValue] == 1)
        {
            self.currentConnectedDevice = [array objectAtIndex:1];
            [self.wlanTable reloadData];
            
            [_skipButton setTitle:NSLocalizedString(@"WLANVIEW_CONFIRMBUTTON",@"") forState:UIControlStateNormal];
            
            self.infoLabel.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"CONNECTEDTO",@"") ,[array objectAtIndex:1]];
        }
        else
        {
            if([[array objectAtIndex:1] length] != 0)
            {
                self.infoLabel.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"UNCONNECTEDTO",@""),[array objectAtIndex:1]];
            }
            else
            {
                self.infoLabel.text = NSLocalizedString(@"UNCONNECTED",@"");
            }
        }
    }
    else
    {
        self.infoLabel.text = NSLocalizedString(@"PARSEERROR",@"");
    }
}

-(void)serviceConnectToWifiCallBack:(NSDictionary*)dicCallBack
{
    NSString * info = nil;
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        info = NSLocalizedString(@"ALERT_WIFIDISCONNECTED",@"");
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue] ||
            [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue])
    {
        info = NSLocalizedString(@"ALERT_CONNECTORDERFAILED",@"");
        _flowerView.hidden = YES;
    }
    else
    {
//        info = NSLocalizedString(@"ALERT_CONNECTINGWAITING",@"");
        
        if(connectStatusTimer == nil && ![connectStatusTimer isValid])
        {
            connectStatusTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(getConnectStatusTimerMethod) userInfo:nil repeats:YES];
            
            [[NSRunLoop currentRunLoop] addTimer:connectStatusTimer forMode:NSDefaultRunLoopMode];
            _flowerView.hidden = NO;
        }
    }
    
    if(info != nil)
    {
        [self.insideView makeToast:info
           duration:3.0
           position:@"bottom"
              title:NSLocalizedString(@"ALERT_TITLE",@"")];
    }
    
//    [self disappearAnimation];
}

-(void)serviceGetWifiConnectStatusCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
//        [self disappearAnimation];
//        
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    NSString * connectstate = [dicCallBack objectForKey:@"connectstate"];
    NSLog(@"connectstate %@",connectstate);
    if([connectstate isEqualToString:@"OK"])
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_CONNECTWIFISUCCESS",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }
        
        _flowerView.hidden = YES;
        
        [self getDeviceInformations];
    }
    else if([connectstate isEqualToString:@"FAIL"] || [connectstate isEqualToString:@"NONE"])
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_CONNECTWIFIFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }
        
        _flowerView.hidden = YES;
        
        [self getDeviceInformations];
    }
    else if([connectstate isEqualToString:@"PAIRFAIL"])
    {
        [self.insideView makeToast:NSLocalizedString(@"ALERT_WRONGPASS",@"")
               duration:3.0
               position:@"bottom"
                  title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }
        
        _flowerView.hidden = YES;
        
        [self getDeviceInformations];
    }
    else
    {
//        if(connectTimeCount > 20)
//        {
//            if(connectStatusTimer != nil && [connectStatusTimer isValid])
//            {
//                [connectStatusTimer invalidate];
//                connectStatusTimer = nil;
//            }
//            _flowerView.hidden = YES;
//            
//            [self.insideView makeToast:NSLocalizedString(@"ALERT_CONNECTWIFIFAILED",@"")
//                   duration:3.0
//                   position:@"bottom"
//                      title:NSLocalizedString(@"ALERT_TITLE",@"")];
//        }
    }
}

#pragma mark -
#pragma mark UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_passwordField resignFirstResponder];
    return YES;
}

@end
